package com.dlc.hardwareprotocol.serialport;

import android.os.Handler;

import androidx.annotation.Nullable;

import com.dlc.hardwareprotocol.serialport.command.RecvCommand;
import com.dlc.hardwareprotocol.serialport.command.SendCommand;
import com.licheedev.serialworker.core.DataReceiver;
import com.licheedev.serialworker.worker.Rs232SerialWorker;

public class MainSerialWorker extends Rs232SerialWorker<SendCommand, RecvCommand> {

    private final Handler mRecvHandler;

    public MainSerialWorker(@Nullable Handler recvHandler) {
        mRecvHandler = recvHandler;
    }

    @Override
    public boolean isMyResponse(SendCommand sendData, RecvCommand recvData) {
        return sendData.getCmd() == recvData.getCmd();
    }

    @Override
    public DataReceiver<RecvCommand> newReceiver() {
        return new MainDataReceiver();
    }

    @Override
    public void onReceiveData(final RecvCommand recvData) {
        // 把数据暴露出去
        if (mReceiveCallback != null) {
            if (mRecvHandler != null) {
                mRecvHandler.post(() -> mReceiveCallback.onReceive(recvData));
            } else {
                mReceiveCallback.onReceive(recvData);
            }
        }
    }

    private ReceiveCallback mReceiveCallback;

    public interface ReceiveCallback {

        void onReceive(RecvCommand recvCommand);

    }

    public void setReceiveCallback(ReceiveCallback receiveCallback) {
        mReceiveCallback = receiveCallback;
    }
}